

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 参考资料 SPOC还有一些参考的文章，都有在相应部分标注。 运行环境  windows10 IDEA 2021.6 专业版 MyBatis3.5.0  获取Demo Gitee：https:&#x2F;&#x2F;gitee.com&#x2F;ccuni&#x2F;mybatis-learn-quick-get-start 一、MyBatis 动态 SQL 实现动态SQL的标签主要有 if、 trim 、 where 、">
<meta property="og:type" content="article">
<meta property="og:title" content="MyBatis 笔记3 动态SQL语句 _ trim标签、foreach标签、choose标签 _ MyBatis缓存机制 _ MyBatis 逆向工程使用案例">
<meta property="og:url" content="http://example.com/2022/01/16/MyBatis%20%E7%AC%94%E8%AE%B03%20%E5%8A%A8%E6%80%81SQL%E8%AF%AD%E5%8F%A5%20_%20trim%E6%A0%87%E7%AD%BE%E3%80%81foreach%E6%A0%87%E7%AD%BE%E3%80%81choose%E6%A0%87%E7%AD%BE%20_%20MyBatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6%20_%20MyBatis%20%E9%80%86%E5%90%91%E5%B7%A5%E7%A8%8B%E4%BD%BF%E7%94%A8%E6%A1%88%E4%BE%8B/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 参考资料 SPOC还有一些参考的文章，都有在相应部分标注。 运行环境  windows10 IDEA 2021.6 专业版 MyBatis3.5.0  获取Demo Gitee：https:&#x2F;&#x2F;gitee.com&#x2F;ccuni&#x2F;mybatis-learn-quick-get-start 一、MyBatis 动态 SQL 实现动态SQL的标签主要有 if、 trim 、 where 、">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/fae8825d78884e36a87197ce277088d9.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/93a33519f621447187ddd71b60073c41.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/29fe244295764f938e9f9af81e4ba29d.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/d0bf779779ca46aeb64032ffd961e76c.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/04e68df113a3487bb99b413e3f1421e3.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/ced83811d5594b4690cd0fcdbb74b16d.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/aec9a78b172a41cd8f359189b99819f3.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/5242b4eece9446f6b92f9d1b63ebd346.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/f58852ada68a4ab3957c565e19fa83e4.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2c08633a4b5d49e098074a95ed7d8762.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/a815f76e96984f889f4c349b45cfe20a.png#pic_center">
<meta property="article:published_time" content="2022-01-16T03:16:50.000Z">
<meta property="article:modified_time" content="2022-08-22T15:46:54.993Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="MyBatis">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/fae8825d78884e36a87197ce277088d9.png#pic_center">
  
  
  
  <title>MyBatis 笔记3 动态SQL语句 _ trim标签、foreach标签、choose标签 _ MyBatis缓存机制 _ MyBatis 逆向工程使用案例 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="MyBatis 笔记3 动态SQL语句 _ trim标签、foreach标签、choose标签 _ MyBatis缓存机制 _ MyBatis 逆向工程使用案例"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-01-16 11:16" pubdate>
          2022年1月16日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          14k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          117 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">MyBatis 笔记3 动态SQL语句 _ trim标签、foreach标签、choose标签 _ MyBatis缓存机制 _ MyBatis 逆向工程使用案例</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><hr>
<p><a target="_blank" rel="noopener" href="http://spoc.wzu.edu.cn/study/initplay/784713.mooc">SPOC</a><br>还有一些参考的文章，都有在相应部分标注。</p>
<h1 id="运行环境"><a href="#运行环境" class="headerlink" title="运行环境"></a>运行环境</h1><hr>
<ul>
<li>windows10</li>
<li>IDEA 2021.6 专业版</li>
<li>MyBatis3.5.0</li>
</ul>
<h1 id="获取Demo"><a href="#获取Demo" class="headerlink" title="获取Demo"></a>获取Demo</h1><hr>
<p>Gitee：<a target="_blank" rel="noopener" href="https://gitee.com/ccuni/mybatis-learn-quick-get-start">https://gitee.com/ccuni/mybatis-learn-quick-get-start</a></p>
<h1 id="一、MyBatis-动态-SQL"><a href="#一、MyBatis-动态-SQL" class="headerlink" title="一、MyBatis 动态 SQL"></a>一、MyBatis 动态 SQL</h1><hr>
<p>实现动态SQL的标签主要有 if、 trim 、 where 、 set 、 choose （when 、 otherwise）、foreach</p>
<h2 id="1-1-if-标签"><a href="#1-1-if-标签" class="headerlink" title="1.1 if 标签"></a>1.1 if 标签</h2><p><strong>基本语法：</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;表达式&quot;</span>&gt;</span>若表达式成立则返回的字符串<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p><strong>功能描述：</strong> 可根据参数的值选择SQL语句执行的参数，是实现动态SQL的关键标签。</p>
<p><strong>使用案例：</strong> 在实现修改功能时，若缺少参数，比如只修改一部分信息的情况，此时的SQL语句需要根据实体类对象的值进行判断，若为NULL则不进行修改，以供应商信息修改为例：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- 修改供应商信息 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">update</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;modifyProvider&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;Provider&quot;</span>&gt;</span><br>    UPDATE smbms_provider<br>    <span class="hljs-tag">&lt;<span class="hljs-name">set</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;proCode!=null&quot;</span>&gt;</span>proCode=#&#123;proCode&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;proName!=null&quot;</span>&gt;</span>proName=#&#123;proName&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;proDesc!=null&quot;</span>&gt;</span>proDesc=#&#123;proDesc&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;proContact!=null&quot;</span>&gt;</span>proContact=#&#123;proContact&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;proPhone!=null&quot;</span>&gt;</span>proPhone=#&#123;proPhone&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;proAddress!=null&quot;</span>&gt;</span>proAddress=#&#123;proAddress&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;proFax!=null&quot;</span>&gt;</span>proFax=#&#123;proFax&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;modifyDate!=null&quot;</span>&gt;</span>modifyDate=#&#123;modifyDate&#125;<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">set</span>&gt;</span><br>    WHERE id=#&#123;id&#125;<br><span class="hljs-tag">&lt;/<span class="hljs-name">update</span>&gt;</span><br></code></pre></td></tr></table></figure>



<h2 id="1-2-where-标签"><a href="#1-2-where-标签" class="headerlink" title="1.2 where 标签"></a>1.2 where 标签</h2><p><strong>基本语法：</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">where</span>&gt;</span><br>	<span class="hljs-comment">&lt;!--...sql语句--&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">where</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p><strong>功能描述：</strong> 简化SQL语句中的where条件判断、只能处理and和or</p>
<p><strong>使用案例：</strong> 以实现根据用户名称和用户角色的查询为例，有可能缺少一个参数</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;queryUserByDSQL&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;User&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;User&quot;</span>&gt;</span><br>    SELECT * FROM smbms_user<br>    <span class="hljs-tag">&lt;<span class="hljs-name">where</span>&gt;</span><br>    	<span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userName != null and userName != &#x27;&#x27;&quot;</span>&gt;</span><br>        	userName like CONCAT(&#x27;%&#x27;, #&#123;userName&#125;, &#x27;%&#x27;)<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userRole != null&quot;</span>&gt;</span><br>        	AND userRole = # &#123;userRole&#125;<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">where</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>注：若不使用 where标签，当 userName为空时，SQL语句为 <code>SELECT * FROM smbms_user WHERE AND ... </code> 则为不合法SQL语句</p>
<h2 id="1-3-set-标签"><a href="#1-3-set-标签" class="headerlink" title="1.3 set 标签"></a>1.3 set 标签</h2><p><strong>基本语法：</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">set</span>&gt;</span><br>    <span class="hljs-comment">&lt;!-- SQL语句 --&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">set</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p><strong>功能描述：</strong> 可以搭配 IF 标签，过滤实体类变量为 NULL的情况。</p>
<p>使用案例可参考IF标签的案例。</p>
<h2 id="1-4-trim-标签"><a href="#1-4-trim-标签" class="headerlink" title="1.4 trim 标签"></a>1.4 trim 标签</h2><p><strong>基本语法：</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">trim</span> <span class="hljs-attr">prefix</span>=<span class="hljs-string">&quot;...&quot;</span> <span class="hljs-attr">suffix</span>=<span class="hljs-string">&quot;...&quot;</span> <span class="hljs-attr">prefixOverrides</span>=<span class="hljs-string">&quot;...&quot;</span> <span class="hljs-attr">suffixOverrides</span>=<span class="hljs-string">&quot;...&quot;</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">trim</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p><strong>功能描述：</strong> 更灵活的去除多余的关键字，可以替代 <code>where</code> 和 <code>set</code></p>
<p><strong>属性说明：</strong></p>
<table>
<thead>
<tr>
<th>属性值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>prefix</td>
<td>前缀，作用是通过自动识别是否有返回值后，在 trim 包含的内容上加上前缀，如此处的where</td>
</tr>
<tr>
<td>suffix</td>
<td>后缀，作用是在trim包含的内容加上后缀</td>
</tr>
<tr>
<td>prefixOverrides</td>
<td>对于 trim 包含内容的首部进行指定内容的忽略</td>
</tr>
<tr>
<td>suffixOverrides</td>
<td>对于 trim 包含内容的尾部进行指定内容的忽略</td>
</tr>
</tbody></table>
<p><strong>使用案例：</strong> </p>
<ul>
<li>更新用户表数据</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">update</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;...&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;User&quot;</span>&gt;</span><br>	UPDATE smbms_user<br>    <span class="hljs-tag">&lt;<span class="hljs-name">trim</span> <span class="hljs-attr">prefix</span> =<span class="hljs-string">&quot;set&quot;</span> <span class="hljs-attr">suffixOverrides</span>=<span class="hljs-string">&quot;,&quot;</span> <span class="hljs-attr">suffix</span>=<span class="hljs-string">&quot;WHERE id = #&#123;id&#125;&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userCode != null&quot;</span>&gt;</span>userCode=#&#123;userCode&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userName != null&quot;</span>&gt;</span>userName=#&#123;userName&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userPassword != null&quot;</span>&gt;</span>userPassword=#&#123;userPassword&#125;,<span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">trim</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">update</span>&gt;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>根据用户名、用户角色查询，其中用户名为模糊查询</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">trim</span> <span class="hljs-attr">prefix</span>=<span class="hljs-string">&quot;WHERE&quot;</span> <span class="hljs-attr">prefixOverrides</span>=<span class="hljs-string">&quot;AND|OR&quot;</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userName != null AND userName != &quot;</span>&gt;</span><br>    	AND userName like CONCAT(&#x27;%&#x27;, #&#123;userName&#125;, &#x27;%&#x27;)<br>    <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userRole != null&quot;</span>&gt;</span><br>    	AND userRole=#&#123;userRole&#125;<br>    <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">trim</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="1-5-foreach-标签"><a href="#1-5-foreach-标签" class="headerlink" title="1.5 foreach 标签"></a>1.5 foreach 标签</h2><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/wt_better/article/details/80941646">可参考这篇博文，内容十分详细</a></p>
<p><strong>基本语法：</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">foreach</span> <span class="hljs-attr">collection</span>=<span class="hljs-string">&quot;...&quot;</span> <span class="hljs-attr">item</span>=<span class="hljs-string">&quot;...&quot;</span> <span class="hljs-attr">open</span>=<span class="hljs-string">&quot;(&quot;</span> <span class="hljs-attr">separator</span>=<span class="hljs-string">&quot;,&quot;</span> <span class="hljs-attr">close</span>=<span class="hljs-string">&quot;)&quot;</span>&gt;</span><br>	#&#123;...&#125;<br><span class="hljs-tag">&lt;/<span class="hljs-name">foreach</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p><strong>功能描述：</strong> 通过遍历Mapper接口传入的对象返回SQL语句</p>
<p><strong>属性说明：</strong></p>
<table>
<thead>
<tr>
<th>属性</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>item</td>
<td>表示集合中每一个元素进行迭代时的别名</td>
</tr>
<tr>
<td>index</td>
<td>指定一个名称，用于表示在迭代过程中，每次迭代到的位置</td>
</tr>
<tr>
<td>open</td>
<td>表示该语句以什么开始（in 条件语句是以 “(“ 开始）</td>
</tr>
<tr>
<td>separator</td>
<td>表示在每次迭代之前以什么符号作为分隔符（ in 条件语句以 “,” 作为分隔符）</td>
</tr>
<tr>
<td>close</td>
<td>表示该语句以什么结束（ in 条件语句是以 “)” 结束）</td>
</tr>
<tr>
<td>collection</td>
<td>该属性必须指定，不同情况下该属性的值不一样，主要有三种情况。</td>
</tr>
</tbody></table>
<p><strong>collection 属性的 三种情况：</strong></p>
<p>（1）传入的参数为List类型，比如<code>List&lt;User&gt;</code>则值指定为<code>list</code>；</p>
<p>（2）传入的参数为数组，比如<code> Integer[]</code> 则值指定为<code>array</code>；</p>
<p>（3）若传入的参数为多个参数，则需把它们封装成一个Map对象进行处理，值指定为 <code>map</code></p>
<h3 id="1-5-1-List-类型"><a href="#1-5-1-List-类型" class="headerlink" title="1.5.1 List 类型"></a>1.5.1 List 类型</h3><p>比如需要查询属于一些用户角色集合内的所有用户，用户角色用整型表示。</p>
<p><code>Mapper.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">List&lt;User&gt; <span class="hljs-title function_">queryForeachByRole</span><span class="hljs-params">(List&lt;Integer&gt; roleList)</span>;<br></code></pre></td></tr></table></figure>

<p><code>Mapper.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;queryForeachByRole&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;User&quot;</span>&gt;</span><br>	SELECT * FROM smbms_user WHERE userRole in <br>    <span class="hljs-tag">&lt;<span class="hljs-name">foreach</span> <span class="hljs-attr">collection</span>=<span class="hljs-string">&quot;list&quot;</span> <span class="hljs-attr">item</span>=<span class="hljs-string">&quot;roleList&quot;</span> <span class="hljs-attr">open</span>=<span class="hljs-string">&quot;(&quot;</span> <span class="hljs-attr">separator</span>=<span class="hljs-string">&quot;,&quot;</span> <span class="hljs-attr">close</span>=<span class="hljs-string">&quot;)&quot;</span>&gt;</span><br>    	#&#123;roleList&#125;<br>    <span class="hljs-tag">&lt;/<span class="hljs-name">foreach</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h3 id="1-5-2-Map-类型"><a href="#1-5-2-Map-类型" class="headerlink" title="1.5.2 Map 类型"></a>1.5.2 Map 类型</h3><p>比如需要插入一个新的用户</p>
<p><code>Mapper.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">int</span> <span class="hljs-title function_">addUserForeach</span><span class="hljs-params">(Map&lt;String, String&gt; map)</span><br></code></pre></td></tr></table></figure>

<p><code>Mapper.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">insert</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;addUserForeach&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;map&quot;</span>&gt;</span><br>	INSERT INTO smbms_user(userName, userRole, gender) VALUES<br>    <span class="hljs-tag">&lt;<span class="hljs-name">foreach</span> <span class="hljs-attr">collection</span>=<span class="hljs-string">&quot;map&quot;</span> <span class="hljs-attr">item</span>=<span class="hljs-string">&quot;value&quot;</span> <span class="hljs-attr">index</span>=<span class="hljs-string">&quot;key&quot;</span> <span class="hljs-attr">separator</span>=<span class="hljs-string">&quot;,&quot;</span>&gt;</span><br>        /*若colecction为map类型， item表示为map的value，index表示为map的key*/<br>    	(#&#123;key&#125;, #&#123;value&#125;)<br>    <span class="hljs-tag">&lt;/<span class="hljs-name">foreach</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">insert</span>&gt;</span><br></code></pre></td></tr></table></figure>



<h2 id="1-6-choose-标签"><a href="#1-6-choose-标签" class="headerlink" title="1.6 choose 标签"></a>1.6 choose 标签</h2><p><strong>基本语法：</strong> </p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">choose</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">when</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;条件1&quot;</span>&gt;</span>...<span class="hljs-tag">&lt;/<span class="hljs-name">when</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">when</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;条件2&quot;</span>&gt;</span>...<span class="hljs-tag">&lt;/<span class="hljs-name">when</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">when</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;条件3&quot;</span>&gt;</span>...<span class="hljs-tag">&lt;/<span class="hljs-name">when</span>&gt;</span><br>   	...<br>    <span class="hljs-tag">&lt;<span class="hljs-name">otherwise</span>&gt;</span>...<span class="hljs-tag">&lt;/<span class="hljs-name">otherwise</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">choose</span>&gt;</span><br></code></pre></td></tr></table></figure>



<p><strong>功能描述：</strong> 相当于 java中的<code>switch </code>语句 ，当 <code>when</code>有条件满足时，就跳出<code>choose</code></p>
<p><strong>使用案例：</strong> 根据用户的名称、编号、创建时间的年份这三个参数的某一个来进行查询，类似于单选框里选择一个参数查询</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;...&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;User&quot;</span>&gt;</span><br>	SELECT * FROM smbms_user WHERE 1=1<br>    <span class="hljs-tag">&lt;<span class="hljs-name">choose</span>&gt;</span><br>    	<span class="hljs-tag">&lt;<span class="hljs-name">when</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userName != null and userName != &#x27;&#x27;&quot;</span>&gt;</span><br>        	AND userName LIKE CONCAT(&#x27;%&#x27;, #&#123;userName&#125;, &#x27;%&#x27;)<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">when</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">when</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;userCode != null and userCode != &#x27;&#x27;&quot;</span>&gt;</span><br>        	AND userCode LIKE CONCAT(&#x27;%&#x27;, #&#123;userCode&#125;, &#x27;%&#x27;)<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">when</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">otherwise</span>&gt;</span><br>        	AND YEAR(creationDate) = YEAR(#&#123;creationDate&#125;)<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">otherwise</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">choose</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h1 id="二、MyBatis-缓存机制"><a href="#二、MyBatis-缓存机制" class="headerlink" title="二、MyBatis 缓存机制"></a>二、MyBatis 缓存机制</h1><hr>
<p><strong>目的：</strong> 为了提高数据库操作的效率</p>
<p><strong>原理：</strong> 第一次查询的数据保存到缓存里（内存），下次要查询相同数据时则直接从缓存中获取，不用在到数据库中取</p>
<p><strong>分类：</strong> </p>
<ul>
<li>一级缓存（在一个session中有效）每个 session独立，默认开启，只能手动关闭</li>
<li>二级缓存（在全局范围内有效） 所有session共享，默认开启，可以在配置中设置</li>
</ul>
<p>原理图</p>
<p><img src="https://img-blog.csdnimg.cn/fae8825d78884e36a87197ce277088d9.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-1-一级缓存"><a href="#2-1-一级缓存" class="headerlink" title="2.1 一级缓存"></a>2.1 一级缓存</h2><p><strong>以下图片转自课件：</strong></p>
<p><img src="https://img-blog.csdnimg.cn/93a33519f621447187ddd71b60073c41.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br><img src="https://img-blog.csdnimg.cn/29fe244295764f938e9f9af81e4ba29d.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>不同session有不同的一级缓存</p>
<p><img src="https://img-blog.csdnimg.cn/d0bf779779ca46aeb64032ffd961e76c.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>查询期间，如果执行增删改查，则会清空缓存区</p>
<p><img src="https://img-blog.csdnimg.cn/04e68df113a3487bb99b413e3f1421e3.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>手动清空缓存区则调用SqlSession对象的clearCache()方法</p>
<h2 id="2-2-二级缓存"><a href="#2-2-二级缓存" class="headerlink" title="2.2 二级缓存"></a>2.2 二级缓存</h2><ul>
<li>基于namespace级别的缓存，一个namespace对应一个二级缓存</li>
<li>工作机制：会话关闭后，数据保存到二级缓存中。新的会话查询信息，就可以查询二级缓存。</li>
<li>开启二级缓存配置</li>
</ul>
<p><code>mybatis-config.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">settings</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;cacheEnabled&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">setting</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">settings</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>namespace标签下使用cache标签</p>
<p><code>mapper.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">&quot;...&quot;</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">cache</span> <span class="hljs-attr">readOnly</span>=<span class="hljs-string">&quot;true&quot;</span>&gt;</span><br>    <br>    <span class="hljs-tag">&lt;/<span class="hljs-name">cache</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>readyOnly 表示保存到缓存的数据不能修改，默认为false，则要让类实现序列化接口</li>
</ul>
<p><img src="https://img-blog.csdnimg.cn/ced83811d5594b4690cd0fcdbb74b16d.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-3-第三方二级缓存"><a href="#2-3-第三方二级缓存" class="headerlink" title="2.3 第三方二级缓存"></a>2.3 第三方二级缓存</h2><ul>
<li><a target="_blank" rel="noopener" href="https://redis.io/">Redis</a></li>
<li><a target="_blank" rel="noopener" href="https://www.ehcache.org/">ehcache</a></li>
</ul>
<h1 id="三、MyBatis逆向工程"><a href="#三、MyBatis逆向工程" class="headerlink" title="三、MyBatis逆向工程"></a>三、MyBatis逆向工程</h1><hr>
<p>MyBatis逆向工程可根据SQL表的单表自动生成MYBatis执行所需要的代码(mapper.java、mapper.xml、pojo等等)</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_39056805/article/details/80585941">可以参考这篇博文，内容十分详细</a></p>
<p>GitHub地址：<a target="_blank" rel="noopener" href="https://github.com/mybatis/generator/releases">MyBatsi generator Release版本</a></p>
<h2 id="3-1-使用案例"><a href="#3-1-使用案例" class="headerlink" title="3.1 使用案例"></a>3.1 使用案例</h2><p>测试的数据表：</p>
<p><img src="https://img-blog.csdnimg.cn/aec9a78b172a41cd8f359189b99819f3.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>（1）导入依赖</p>
<p><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- MyBatis 逆向工程 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mybatis.generator<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mybatis-generator<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.4.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mybatis.generator<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mybatis-generator-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.4.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>



<p>（2）设置配置文件 <code>resources/generatorConfig.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=<span class="hljs-string">&quot;1.0&quot;</span> encoding=<span class="hljs-string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-keyword">generatorConfiguration</span> <span class="hljs-keyword">PUBLIC</span> <span class="hljs-string">&quot;-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN&quot;</span> <span class="hljs-string">&quot;http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd&quot;</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">generatorConfiguration</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">context</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;DB2Tables&quot;</span> <span class="hljs-attr">targetRuntime</span>=<span class="hljs-string">&quot;MyBatis3&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">commentGenerator</span>&gt;</span><br>            <span class="hljs-comment">&lt;!-- 是否去除自动生成的注释 --&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;suppressAllComments&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span>/&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">commentGenerator</span>&gt;</span><br><br>        <span class="hljs-comment">&lt;!-- Mysql数据库连接的信息：驱动类、连接地址、用户名、密码 --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">jdbcConnection</span> <span class="hljs-attr">driverClass</span>=<span class="hljs-string">&quot;com.mysql.jdbc.Driver&quot;</span></span><br><span class="hljs-tag">                        <span class="hljs-attr">connectionURL</span>=<span class="hljs-string">&quot;jdbc:mysql://localhost:3306/smbms&quot;</span></span><br><span class="hljs-tag">                        <span class="hljs-attr">userId</span>=<span class="hljs-string">&quot;root&quot;</span></span><br><span class="hljs-tag">                        <span class="hljs-attr">password</span>=<span class="hljs-string">&quot;数据库密码&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">jdbcConnection</span>&gt;</span><br><br>        <span class="hljs-comment">&lt;!-- 默认为false，把JDBC DECIMAL 和NUMERIC类型解析为Integer，为true时</span><br><span class="hljs-comment">        把JDBC DECIMAL 和NUMERIC类型解析为java.math.BigDecimal --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">javaTypeResolver</span> &gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;forceBigDecimals&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;false&quot;</span> /&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">javaTypeResolver</span>&gt;</span><br><br>        <span class="hljs-comment">&lt;!-- targetProject：生成POJO类的位置 --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">javaModelGenerator</span> <span class="hljs-attr">targetPackage</span>=<span class="hljs-string">&quot;com.uni.pojo&quot;</span> <span class="hljs-attr">targetProject</span>=<span class="hljs-string">&quot;.\src\main\java&quot;</span>&gt;</span><br>            <span class="hljs-comment">&lt;!-- enableSubPackages:是否让schema作为包的后缀 --&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;enableSubPackages&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;false&quot;</span> /&gt;</span><br>            <span class="hljs-comment">&lt;!-- 从数据库返回的值被清理前后的空格 --&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;trimStrings&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span> /&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">javaModelGenerator</span>&gt;</span><br><br>        <span class="hljs-comment">&lt;!-- targetProject：mapper映射文件生成的位置 --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">sqlMapGenerator</span> <span class="hljs-attr">targetPackage</span>=<span class="hljs-string">&quot;com.uni.dao.address&quot;</span>  <span class="hljs-attr">targetProject</span>=<span class="hljs-string">&quot;.\src\main\java&quot;</span>&gt;</span><br>            <span class="hljs-comment">&lt;!-- enableSubPackages:是否让schema作为包的后缀 --&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;enableSubPackages&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;false&quot;</span> /&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">sqlMapGenerator</span>&gt;</span><br><br>        <span class="hljs-comment">&lt;!-- targetProject：mapper接口生成的位置 --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">javaClientGenerator</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;XMLMAPPER&quot;</span> <span class="hljs-attr">targetPackage</span>=<span class="hljs-string">&quot;com.uni.dao.address&quot;</span>  <span class="hljs-attr">targetProject</span>=<span class="hljs-string">&quot;.\src\main\java&quot;</span>&gt;</span><br>            <span class="hljs-comment">&lt;!-- enableSubPackages:是否让schema作为包的后缀 --&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;enableSubPackages&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;false&quot;</span> /&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">javaClientGenerator</span>&gt;</span><br>        <br>        <span class="hljs-comment">&lt;!-- 指定数据表--&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">table</span> <span class="hljs-attr">schema</span>=<span class="hljs-string">&quot;smbms_address&quot;</span> <span class="hljs-attr">tableName</span>=<span class="hljs-string">&quot;smbms_address&quot;</span> <span class="hljs-attr">domainObjectName</span>=<span class="hljs-string">&quot;Address&quot;</span> &gt;</span><br>          <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;useActualColumnNames&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span>/&gt;</span><br>          <span class="hljs-tag">&lt;<span class="hljs-name">generatedKey</span> <span class="hljs-attr">column</span>=<span class="hljs-string">&quot;ID&quot;</span> <span class="hljs-attr">sqlStatement</span>=<span class="hljs-string">&quot;DB2&quot;</span> <span class="hljs-attr">identity</span>=<span class="hljs-string">&quot;true&quot;</span> /&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">context</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">generatorConfiguration</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>（3）设置生成类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.generator;<br><br><span class="hljs-keyword">import</span> org.mybatis.generator.api.MyBatisGenerator;<br><span class="hljs-keyword">import</span> org.mybatis.generator.config.Configuration;<br><span class="hljs-keyword">import</span> org.mybatis.generator.config.xml.ConfigurationParser;<br><span class="hljs-keyword">import</span> org.mybatis.generator.internal.DefaultShellCallback;<br><br><span class="hljs-keyword">import</span> java.io.File;<br><span class="hljs-keyword">import</span> java.util.ArrayList;<br><span class="hljs-keyword">import</span> java.util.List;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">GeneratorTest</span> &#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">generator</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        List&lt;String&gt; warnings = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;String&gt;();<br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">overwrite</span> <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;<br>        <span class="hljs-comment">// 指定配置文件</span><br><br>        <span class="hljs-type">File</span> <span class="hljs-variable">configFile</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(<span class="hljs-built_in">this</span>.getClass().getResource(<span class="hljs-string">&quot;/&quot;</span>).getPath() + <span class="hljs-string">&quot;generatorConfig.xml&quot;</span>);<br><br>        <span class="hljs-type">ConfigurationParser</span> <span class="hljs-variable">cp</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ConfigurationParser</span>(warnings);<br>        <span class="hljs-type">Configuration</span> <span class="hljs-variable">config</span> <span class="hljs-operator">=</span> cp.parseConfiguration(configFile);<br>        <span class="hljs-type">DefaultShellCallback</span> <span class="hljs-variable">callback</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">DefaultShellCallback</span>(overwrite);<br>        <span class="hljs-type">MyBatisGenerator</span> <span class="hljs-variable">myBatisGenerator</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyBatisGenerator</span>(config, callback, warnings);<br>        myBatisGenerator.generate(<span class="hljs-literal">null</span>);<br>    &#125;<br><br>    <span class="hljs-comment">// 执行main方法以生成代码</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-type">GeneratorTest</span> <span class="hljs-variable">g</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">GeneratorTest</span>();<br>            g.generator();<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>运行结果：</p>
<p><img src="https://img-blog.csdnimg.cn/5242b4eece9446f6b92f9d1b63ebd346.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/594c7d13089b4fddaea3661ba9104c2c.png#pic_Center#pic_center">https://img-blog.csdnimg.cn/594c7d13089b4fddaea3661ba9104c2c.png#pic_Center#pic_center</a> &#x3D;50%x)</p>
<p>自动生成的 <code>AddressMapper.java</code>内容</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.dao.address;<br><br><span class="hljs-keyword">import</span> com.uni.pojo.Address;<br><span class="hljs-keyword">import</span> com.uni.pojo.AddressExample;<br><span class="hljs-keyword">import</span> java.util.List;<br><span class="hljs-keyword">import</span> org.apache.ibatis.annotations.Param;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">AddressMapper</span> &#123;<br>    <span class="hljs-type">long</span> <span class="hljs-title function_">countByExample</span><span class="hljs-params">(AddressExample example)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">deleteByExample</span><span class="hljs-params">(AddressExample example)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">deleteByPrimaryKey</span><span class="hljs-params">(Long id)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">insert</span><span class="hljs-params">(Address record)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">insertSelective</span><span class="hljs-params">(Address record)</span>;<br><br>    List&lt;Address&gt; <span class="hljs-title function_">selectByExample</span><span class="hljs-params">(AddressExample example)</span>;<br><br>    Address <span class="hljs-title function_">selectByPrimaryKey</span><span class="hljs-params">(Long id)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">updateByExampleSelective</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;record&quot;)</span> Address record, <span class="hljs-meta">@Param(&quot;example&quot;)</span> AddressExample example)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">updateByExample</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;record&quot;)</span> Address record, <span class="hljs-meta">@Param(&quot;example&quot;)</span> AddressExample example)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">updateByPrimaryKeySelective</span><span class="hljs-params">(Address record)</span>;<br><br>    <span class="hljs-type">int</span> <span class="hljs-title function_">updateByPrimaryKey</span><span class="hljs-params">(Address record)</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>生成的pojo类没有toString方法，需要自己添加。</p>
<p>生成了两个实体类，<code>Address.java</code>、<code>AdressExample.java</code>，前者是对应数据表字段的一些变量，而后者的内容如下：</p>
<p><code>AddressExample.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">AddressExample</span> &#123;<br>    <span class="hljs-keyword">protected</span> String orderByClause;<br><br>    <span class="hljs-keyword">protected</span> <span class="hljs-type">boolean</span> distinct;<br><br>    <span class="hljs-keyword">protected</span> List&lt;Criteria&gt; oredCriteria;<br> 	<span class="hljs-comment">// ... 还有很多的方法，笔者这里是700多行   </span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>根据参考文章，Example后缀的实体类是用于生成一个Criteria对象来设置查询条件</p>
<h2 id="3-2-查询测试"><a href="#3-2-查询测试" class="headerlink" title="3.2 查询测试"></a>3.2 查询测试</h2><p><code>MyBatisUtil.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.utils;<br><span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSession;<br><span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;<br><span class="hljs-keyword">import</span> org.apache.ibatis.io.Resources;<br><span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSessionFactoryBuilder;<br><br><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.io.InputStream;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyBatisUtil</span> &#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> SqlSessionFactory factory;<br><br>    <span class="hljs-comment">/** 单例模式创建工厂 只执行一次**/</span><br>    <span class="hljs-keyword">static</span> &#123;<br>        <span class="hljs-keyword">try</span>&#123;<br>            <span class="hljs-type">String</span> <span class="hljs-variable">resource</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;mybatis-config.xml&quot;</span>;<br>            <span class="hljs-comment">// 1. 获取 mybatsi-config.xml 的输入流</span><br>            <span class="hljs-type">InputStream</span> <span class="hljs-variable">is</span> <span class="hljs-operator">=</span> Resources.getResourceAsStream(resource);<br>            <span class="hljs-comment">// 2. 创建 SqlSessionFactory对象，完成对配置文件的读取</span><br>            factory = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SqlSessionFactoryBuilder</span>().build(is);<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> SqlSession <span class="hljs-title function_">getSession</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> factory.openSession();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>根据ID查询</strong></p>
<p>方法：<code>selectByPrimaryKey(Long  itemId)</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni;<br><br><span class="hljs-keyword">import</span> com.uni.dao.address.AddressMapper;<br><span class="hljs-keyword">import</span> com.uni.pojo.Address;<br><span class="hljs-keyword">import</span> com.uni.utils.MyBatisUtil;<br><span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSession;<br><span class="hljs-keyword">import</span> org.junit.Test;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">TestAddressMapper</span> &#123;<br><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">SqlSession</span> <span class="hljs-variable">sqlSession</span> <span class="hljs-operator">=</span> MyBatisUtil.getSession();<br>        <span class="hljs-type">AddressMapper</span> <span class="hljs-variable">mapper</span> <span class="hljs-operator">=</span> sqlSession.getMapper(AddressMapper.class);<br>        <span class="hljs-type">Address</span> <span class="hljs-variable">address</span> <span class="hljs-operator">=</span> mapper.selectByPrimaryKey(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Long</span>(<span class="hljs-number">1</span>));<br>        System.out.println(address);<br>        sqlSession.close();<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><strong>运行结果：</strong></p>
<p><img src="https://img-blog.csdnimg.cn/f58852ada68a4ab3957c565e19fa83e4.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>根据Example对象查询所有的数据</strong></p>
<p>方法：<code>selectByExample(TbItemDescExample  example)</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testExample</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-type">SqlSession</span> <span class="hljs-variable">sqlSession</span> <span class="hljs-operator">=</span> MyBatisUtil.getSession();<br>    <span class="hljs-type">AddressMapper</span> <span class="hljs-variable">mapper</span> <span class="hljs-operator">=</span> sqlSession.getMapper(AddressMapper.class);<br>    <span class="hljs-type">AddressExample</span> <span class="hljs-variable">example</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">AddressExample</span>();<br>    List&lt;Address&gt; addresses = mapper.selectByExample(example);<br>    addresses.forEach(ad -&gt; System.out.println(ad));<br>    sqlSession.close();<br>&#125;<br></code></pre></td></tr></table></figure>



<p>可以通过 Example对象创建 criteria （标准）的对象，然后通过调用and前缀的一些方法去设置查询的条件</p>
<p>其中的方法都是根据数据表的字段生成的，然后条件的限制也是固定的，比如<code>IsNotNull()</code> 、<code>IsNull() </code>等等</p>
<p><img src="https://img-blog.csdnimg.cn/2c08633a4b5d49e098074a95ed7d8762.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>实现模糊查询</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testExample</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-type">SqlSession</span> <span class="hljs-variable">sqlSession</span> <span class="hljs-operator">=</span> MyBatisUtil.getSession();<br>    <span class="hljs-type">AddressMapper</span> <span class="hljs-variable">mapper</span> <span class="hljs-operator">=</span> sqlSession.getMapper(AddressMapper.class);<br>    <span class="hljs-type">AddressExample</span> <span class="hljs-variable">example</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">AddressExample</span>();<br>    AddressExample.<span class="hljs-type">Criteria</span> <span class="hljs-variable">criteria</span> <span class="hljs-operator">=</span> example.createCriteria();<br>    <span class="hljs-comment">// 模糊查询</span><br>    criteria.andContactLike(<span class="hljs-string">&quot;%丽%&quot;</span>);<br>    List&lt;Address&gt; addresses = mapper.selectByExample(example);<br>    addresses.forEach(ad -&gt; System.out.println(ad));<br>    sqlSession.close();<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>运行结果：</strong></p>
<p><img src="https://img-blog.csdnimg.cn/a815f76e96984f889f4c349b45cfe20a.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>由此可见，Mybatis逆向工程的作用很大，可以自动生成支持查询的方法，其实基本的CRUD操作应该都是支持的，由于是刚入门，笔者就不继续深入了。但目前来说，逆向工程只针对于单张表，所以要多表联合的话就需要自己在添加一些成员变量以及SQL注入了。满足平时的CRUD应该是没问题的。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/ORM/" class="category-chain-item">ORM</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/MyBatis/">#MyBatis</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>MyBatis 笔记3 动态SQL语句 _ trim标签、foreach标签、choose标签 _ MyBatis缓存机制 _ MyBatis 逆向工程使用案例</div>
      <div>http://example.com/2022/01/16/MyBatis 笔记3 动态SQL语句 _ trim标签、foreach标签、choose标签 _ MyBatis缓存机制 _ MyBatis 逆向工程使用案例/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年1月16日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/16/Hadoop%20_%20%E9%9B%86%E7%BE%A4%E9%85%8D%E7%BD%AE%EF%BC%88%E5%9B%9B%EF%BC%89%E5%90%AF%E5%8A%A8%E6%B5%8B%E8%AF%95%E5%AE%8C%E5%85%A8%E5%88%86%E5%B8%83%E5%BC%8F%E9%9B%86%E7%BE%A4%20_%20%E7%BC%96%E5%86%99%20Shell%20%E8%84%9A%E6%9C%AC%E4%B8%80%E9%94%AE%E5%90%AF%E5%8A%A8%E9%9B%86%E7%BE%A4%20_%20Hadoop%20%E9%9B%86%E7%BE%A4%E5%B8%B8%E7%94%A8%E8%84%9A%E6%9C%AC/" title="Hadoop _ 集群配置（四）启动测试完全分布式集群 _ 编写 Shell 脚本一键启动集群 _ Hadoop 集群常用脚本">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Hadoop _ 集群配置（四）启动测试完全分布式集群 _ 编写 Shell 脚本一键启动集群 _ Hadoop 集群常用脚本</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/01/15/Hadoop%20_%20%E9%9B%86%E7%BE%A4%E9%85%8D%E7%BD%AE%EF%BC%88%E4%BA%8C%EF%BC%89SSH%E5%85%8D%E5%AF%86%E7%99%BB%E9%99%86%E5%8E%9F%E7%90%86%E4%BB%A5%E5%8F%8A%E6%93%8D%E4%BD%9C%20_%20%E5%85%AC%E9%92%A5%E4%B8%8E%E7%A7%81%E9%92%A5/" title="Hadoop _ 集群配置（二）SSH免密登陆原理以及操作 _ 公钥与私钥">
                        <span class="hidden-mobile">Hadoop _ 集群配置（二）SSH免密登陆原理以及操作 _ 公钥与私钥</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
